package com.woniuxy.user.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.request.ResponseResult;
import com.woniuxy.commons.request.StateCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无权限处理器
 */

@Slf4j
@RestControllerAdvice
public class AccessDeniedExceptionHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ResponseResult<Object> responseResult = new ResponseResult<>();
        responseResult.setCode(StateCode.NO_PERMS);
        responseResult.setMessage("没有权限");
        //
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(responseResult));
    }
}